package com.haierp.task;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.enums.ItemStatus;
import com.haierp.mapper.ItemMapper;
import com.haierp.mapper.ShippingOrderMapper;
import com.haierp.mapper.ShippingTrackMapper;
import com.haierp.model.Item;
import com.haierp.model.ShippingOrder;
import com.haierp.model.ShippingTrack;
import com.haierp.model.TaskDailyOrderHistory;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IShippingOrderService;
import com.haierp.service.IShippingTrackService;
import com.haierp.service.ITaskDailyOrderHistoryService;
import com.haierp.service.ITaskDailyOrderService;
import com.haierp.service.ITaskDailyService;
import com.haierp.service.ITaskNoStockReportService;
import com.haierp.service.item.IOuterItemService;
import com.haierp.service.logistics.IFadRoadService;
import com.haierp.service.logistics.IHaihuService;
import com.haierp.service.logistics.ISiFangService;
import com.haierp.util.DateUtil;
import com.haierp.util.ExpressUtil;
import com.haierp.util.MapUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 根据当前订单以及库存情况计算当前采购所需
 * @author liuyang
 *
 */
@Component
public class AutoCreateTaskDailyOrderTask {
	protected Logger logger = LogManager.getLogger(getClass());
	@Autowired
	private ITaskDailyOrderService taskDailyOrderService;
	@Autowired
	private ITaskDailyOrderHistoryService taskDailyOrderHistoryService;
	@Autowired
	private ITaskDailyService taskDailyService;
	@Autowired
	private ItemMapper itemMapper;
	@Autowired
	private IOuterItemService outerItemService;
	@Autowired
	private IHaihuService haiHuService;
	@Autowired
	private IShippingOrderService shippingOrderService;
	@Autowired
	private ShippingTrackMapper shippingTrackMapper;
	@Autowired
	private ShippingOrderMapper shippingOrderMapper;
	@Autowired
	private ITaskNoStockReportService taskNoStockReportService;
	@Autowired
	private ISiFangService siFangService;
	@Autowired
	private IFadRoadService fadRoadService;
	@Autowired
	private IShippingTrackService shippingTrackService;
	@Autowired
	private IErpOrderService erpOrderService;
	//每天凌晨00:01:00 执行一次
	@Scheduled(cron = "0 1 0 ? * *")
	public void run() {
		//自动关闭那些过期的采购计划
		//logger.info("定时任务：自动关闭那些过期的采购计划===>Start");
		//taskDailyService.autoCloseTaskDaily();
		//logger.info("定时任务：自动关闭那些过期的采购计划===>End");
		
		//自动同步商品到有赞
		logger.info("定时任务：自动同步商品到有赞===>Start");
		sysAllItemSale();
		logger.info("定时任务：自动同步商品到有赞===>End");
		
		//每天凌晨跟新每日未备货的商品数量和未备货的商品sku 数量   (已挪到BI里面)
		//logger.info("定时任务：定时任务插入统计每日未入库商品和sku统计====>Start");
		//taskNoStockReportService.insertTaskNoStockReport();
		//logger.info("定时任务：定时任务插入统计每日未入库商品和sku统计====>End");
		
		//每天凌晨跟新备货三天超时的子订订单
		logger.info("定时任务：定时任务跟新备货状态====>Start");
		erpOrderService.updateShippingTimeLaterOrder();
		logger.info("定时任务：定时任务跟新备货状态====>End");
	}

	//每天凌晨00:03:00 执行一次
	@Scheduled(cron = "0 3 0 ? * *")
	public void runTaskDailyOrder() {
		logger.info("定时任务：根据当前订单以及库存情况计算当前采购所需===>Start --- 需要执行，涉及到未完成采购管理功能");
		List<TaskDailyOrderHistory> taskDailyOrderListInsert =taskDailyOrderService.createTaskDailyOrder();
		taskDailyOrderHistoryService.insertBatch(taskDailyOrderListInsert);
		logger.info("定时任务：根据当前订单以及库存情况计算当前采购所需===>End");
	}


	/**
	 * 未完成采购单的商品
	 */
	//每天凌晨00:30:00 执行一次
	@Scheduled(cron = "0 45 23 ? * *")
	public void uncompleteTaskDailyOrder() {
		taskDailyOrderHistoryService.addNocomplestTaskDailyOrder();
	}
	
	/**
	 * 上架可售的商品，下架不可售的商品
	 */
	private void sysAllItemSale() {
		//根据销售时间设置商品是否可售
		itemMapper.updateItemSale();
		itemMapper.updateItemNotSale();
		
		//可售，新建状态
		Item tjItem = new Item();
		tjItem.setIsSale(1);
		tjItem.setCompanyId(1L);//所属公司
		tjItem.setStatus(ItemStatus.INIT.getCode());
		EntityWrapper<Item> entityWrapperInit = new EntityWrapper<Item>();
		entityWrapperInit.setEntity(tjItem);
		List<Item> itemListInit =  itemMapper.selectList(entityWrapperInit);
		if(itemListInit.size()>0) {
			itemListInit.forEach(item -> {
				try {
					outerItemService.synItemYouzan(item.getId());
				} catch(Exception e) {
					logger.error("商品定时同步有赞ItemId:" + item.getId(), e);
				}
			});
		}
		
		//可售
		tjItem = new Item();
		tjItem.setIsSale(1);
		tjItem.setCompanyId(1L);
		//tjItem.setStatus(ItemStatus.DELISTING.getCode());
		EntityWrapper<Item> entityWrapperDelisting = new EntityWrapper<Item>();
		entityWrapperDelisting.setEntity(tjItem);
		List<Item> itemListDelisting =  itemMapper.selectList(entityWrapperDelisting);
		if(itemListDelisting.size()>0) {
			itemListDelisting.forEach(item -> {
				try {
					outerItemService.listingYouzan(item);
				} catch(Exception e) {
					logger.error("商品定时上架有赞ItemId:" + item.getId(), e);
				}
			});
		}
		
		//不可售，上架状态
		tjItem = new Item();
		tjItem.setIsSale(0);
		tjItem.setCompanyId(1L);
		tjItem.setStatus(ItemStatus.LISTING.getCode());
		EntityWrapper<Item> entityWrapperListing = new EntityWrapper<Item>();
		entityWrapperListing.setEntity(tjItem);
		List<Item> itemListListing =  itemMapper.selectList(entityWrapperListing);
		if(itemListListing.size()>0) {
			itemListListing.forEach(item -> {
				try {
					outerItemService.delistingYouzan(item);
				} catch(Exception e) {
					logger.error("商品定时下架有赞ItemId:" + item.getId(), e);
				}
			});
		}
	}
	//每天凌晨00:18:15 执行一次暂时单号每天限制抓取2000条
    //@Scheduled(cron = "0 15 18 * * ?")
	public void runUpdateShippingTrack() {
		logger.info("定时任务：更新写入国内物流运输轨迹===>Start");
		List<ShippingTrack> shippingTrackList = shippingTrackMapper.queryStatus();
		Map<String, String> categorymap = MapUtil.getCategoryKuaiDi();
		String inlandExpressId = "";
		for (int i = 0; i < shippingTrackList.size(); i++) {
		if (StringUtil.isNotBlank(shippingTrackList.get(i).getInlandExpressId())
					&& StringUtil.isNotBlank(shippingTrackList.get(i).getInlandExpressNo())
					&& !shippingTrackList.get(i).getInlandExpressId().contains("haihu")) {
				inlandExpressId = shippingTrackList.get(i).getInlandExpressId();
				if (categorymap.get(inlandExpressId) != null) {
					inlandExpressId = categorymap.get(inlandExpressId);
				}

				try {
					String info = "";
					if ("tiantian".equals(inlandExpressId) || "huitongkuaidi".equals(inlandExpressId)) {
						info = ExpressUtil.callbackLogisticsTrajectory(inlandExpressId,
								shippingTrackList.get(i).getInlandExpressNo());
					} else {
						info = ExpressUtil.getOrderTracesByJson(inlandExpressId,
								shippingTrackList.get(i).getInlandExpressNo());
					}
					Date date = null;
					if(StringUtils.isNotBlank(info)){
						JSONObject param = JSONObject.fromObject(info);
						if(param.containsKey("data")){
							JSONArray jsonArrayss = param.getJSONArray("data");
							for (int j = 0; j < jsonArrayss.size(); j++) {
								JSONObject object2 = jsonArrayss.getJSONObject(j);
								if(String.valueOf(object2.get("context")).contains("签收")){
									date = DateUtil.parseDate(object2.getString("time"));
								}
							}
						}else{
							String  one = (String) param.get("param");
							if(one != null){
								JSONArray jsonArrayss = param.getJSONArray("param");
								for (int j = 0; j < jsonArrayss.size(); j++) {
									JSONObject object2 = jsonArrayss.getJSONObject(j);
									if(String.valueOf(object2.get("AcceptStation")).contains("签收")){
										date = DateUtil.parseDate(object2.getString("AcceptTime"));
									}
								}
							}

						}
					}
					if(date != null){
						ShippingTrack  one = shippingTrackList.get(i);
						one.setGmtModify(date);
						shippingTrackService.updateSelectiveById(one);
						System.out.println(one.getShippingNo());
					}
					if (info.contains("签收")) {
						shippingOrderMapper.updateStatusByShippingNo(shippingTrackList.get(i).getShippingNo());
					}
					shippingTrackMapper.updateInfo(info, shippingTrackList.get(i).getShippingNo());
					Thread.sleep(100);
				} catch (Exception e) {
					logger.error("抓取物流轨迹定时任务(非海狐)", e);
				}

			}
		}

	}
    
    //抓取4px物流轨迹
    @Scheduled(cron = "0 30 17 * * ?")
   	public void runFourPxShippingTrack() {
   		logger.info("定时任务：更新写入4PX轨迹===>Start");
		List<ShippingOrder> Flist = shippingOrderService.queryAllFourPx();//所有走4PX的
		if(CollectionUtils.isNotEmpty(Flist)){
			for (ShippingOrder shippingOrder : Flist) {
				try {
					siFangService.shippingTrack(shippingOrder.getShippingNo());
					Thread.sleep(100);
				} catch (Exception e) {
					logger.error("抓取物流轨迹定时任务(4PX)", e);
				}
			}
		}
   		logger.info("定时任务：更新写入4PX轨迹===>End");
   	}
    //抓取联邦物流轨迹
   //@Scheduled(cron = "0 30 19 * * ?")
   	public void runFadRoadPxShippingTrack() {
   		logger.info("定时任务：更新写入国内物流运输轨迹===>Start");
		List<ShippingOrder> Fadlist = shippingOrderService.queryAllFad();//所有联邦转运
		if(CollectionUtils.isNotEmpty(Fadlist)){
			for (ShippingOrder shippingOrder : Fadlist) {
				try {
					fadRoadService.shippingTrack(shippingOrder.getShippingNo());
					Thread.sleep(100);
				} catch (Exception e) {
					logger.error("抓取物流轨迹定时任务(联邦转运)", e);

				}
			}
		}
		logger.info("定时任务：更新写入国内物流运输轨迹===>End");
   	}
}
